package com.tanhua.dubbo.util;

import com.tanhua.domain.mongo.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

/**
 * @author liuyp
 * @date 2021/01/30
 */
@Component
public class IdSequence {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取指定集合的自增序列值
     * @param collName 集合名称
     * @return 自增的序列值
     */
    public Long getNextId(String collName){
        Query query = new Query(Criteria.where("collName").is(collName));
        Update update = new Update().inc("seqId", 1);

        //设置选项
        FindAndModifyOptions options = new FindAndModifyOptions();
        //  如果集合里没有此记录，是否新增进去
        options.upsert(true);
        //  是否修改后获取最新的值
        options.returnNew(true);
        Sequence sequence = mongoTemplate.findAndModify(query, update, options, Sequence.class);
        return sequence.getSeqId();
    }
}
